package cn.iocoder.yudao.module.ao.controller.admin.classdiscipline.vo;

import lombok.*;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.validation.constraints.*;
import com.alibaba.excel.annotation.*;

/**
 * 课堂纪律登记 Excel 导入 Request VO
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = false) // 设置 chain = false，避免导入有问题
public class ClassDisciplineImportReqVO {

    @ExcelProperty("记录编号")
    private String recordNumber;

    @ExcelProperty("填表时间")
    private String fillTimeStr;

    @ExcelProperty("班级：高技班级")
    @NotEmpty(message = "班级不能为空")
    private String className;

    @ExcelProperty("节次")
    private String classSessionStr;

    @ExcelProperty("晚修节次")
    private String eveningSessionStr;

    @ExcelProperty("未入袋手机（应交未交的）(台)")
    private String unbaggedPhonesStr;

    @ExcelProperty("未到人数（含所有未到）(人)")
    private String absentCountStr;

    @ExcelProperty("病假+学生会+义工队+走读人数(人)")
    private String specialAbsentCountStr;

    @ExcelProperty("上课是否行礼")
    private String isSaluteStr;

    @ExcelProperty("上课是否点名")
    private String isRollCallStr;

    @ExcelProperty("布置且展示了作业")
    private String isAssignShowHomeworkStr;

    @ExcelProperty("晚自习展示作业内容")
    private String eveningHomeworkContent;

    @ExcelProperty("备注")
    private String remark;

    @ExcelProperty("图片链接")
    private String imageUrl;

    @ExcelProperty("处理进度")
    private String processStatus;

    @ExcelProperty("填表人")
    private String filler;

    // 数据转换方法
    public Long getRecordId() {
        if (recordNumber == null || recordNumber.trim().isEmpty()) {
            return null;
        }
        try {
            String cleanValue = recordNumber.replaceAll("[^0-9]", "");
            if (cleanValue.isEmpty()) {
                return null;
            }
            return Long.parseLong(cleanValue);
        } catch (NumberFormatException e) {
            System.out.println("记录编号格式错误：" + recordNumber);
            return null;
        }
    }

    public Integer getClassSession() {
        return parseInteger(classSessionStr, "节次");
    }

    public Integer getEveningSession() {
        return parseInteger(eveningSessionStr, "晚修节次");
    }

    public Integer getUnbaggedPhones() {
        return parseInteger(unbaggedPhonesStr, "未入袋手机数量");
    }

    public Integer getAbsentCount() {
        return parseInteger(absentCountStr, "未到人数");
    }

    public Integer getSpecialAbsentCount() {
        return parseInteger(specialAbsentCountStr, "特殊请假人数");
    }

    public Boolean getIsSalute() {
        return parseBoolean(isSaluteStr, "是否敬礼");
    }

    public Boolean getIsRollCall() {
        return parseBoolean(isRollCallStr, "是否点名");
    }

    public Boolean getIsAssignShowHomework() {
        return parseBoolean(isAssignShowHomeworkStr, "是否布置展示作业");
    }

    public LocalDateTime getFillTime() {
        if (fillTimeStr == null || fillTimeStr.trim().isEmpty()) {
            System.out.println("警告：填表时间为空，该条记录将无法导入");
            return null; // 如果没有填表时间，返回null（必填字段）
        }
        
        try {
            // 尝试多种日期时间格式
            String cleanValue = fillTimeStr.trim();
            
            // 标准化时间格式：处理单数字的小时和分钟 (例如: 7:55 -> 07:55)
            cleanValue = normalizeTimeFormat(cleanValue);
            
            // 格式1: yyyy-MM-dd HH:mm:ss
            try {
                return LocalDateTime.parse(cleanValue, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e1) {
                // 格式2: yyyy/MM/dd HH:mm:ss
                try {
                    return LocalDateTime.parse(cleanValue, DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
                } catch (Exception e2) {
                    // 格式3: yyyy-MM-dd HH:mm (补充秒)
                    try {
                        return LocalDateTime.parse(cleanValue + ":00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    } catch (Exception e3) {
                        // 格式4: yyyy/MM/dd HH:mm (补充秒)
                        try {
                            return LocalDateTime.parse(cleanValue + ":00", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
                        } catch (Exception e4) {
                            // 格式5: yyyy-MM-dd (补充时间)
                            try {
                                return LocalDateTime.parse(cleanValue + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                            } catch (Exception e5) {
                                // 格式6: yyyy/MM/dd (补充时间)
                                try {
                                    return LocalDateTime.parse(cleanValue + " 00:00:00", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
                                } catch (Exception e6) {
                                    System.out.println("填表时间格式错误：" + fillTimeStr + "，请使用格式：yyyy-MM-dd HH:mm:ss");
                                    return null; // 格式错误返回null
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("填表时间解析失败：" + fillTimeStr);
            return null; // 解析失败返回null
        }
    }
    
    /**
     * 标准化时间格式：将单数字的小时和分钟补充为两位数
     * 例如: "2025-10-31 7:55" -> "2025-10-31 07:55"
     *       "2025-10-31 7:5" -> "2025-10-31 07:05"
     */
    private String normalizeTimeFormat(String timeStr) {
        if (timeStr == null || !timeStr.contains(" ")) {
            return timeStr; // 没有时间部分，直接返回
        }
        
        try {
            String[] parts = timeStr.split(" ");
            if (parts.length < 2) {
                return timeStr;
            }
            
            String datePart = parts[0]; // 日期部分
            String timePart = parts[1]; // 时间部分
            
            // 处理时间部分: H:mm 或 H:mm:ss
            String[] timeParts = timePart.split(":");
            if (timeParts.length >= 2) {
                // 补充小时为两位数
                String hour = timeParts[0].length() == 1 ? "0" + timeParts[0] : timeParts[0];
                // 补充分钟为两位数
                String minute = timeParts[1].length() == 1 ? "0" + timeParts[1] : timeParts[1];
                // 补充秒为两位数（如果存在）
                String second = timeParts.length >= 3 
                    ? (timeParts[2].length() == 1 ? "0" + timeParts[2] : timeParts[2]) 
                    : null;
                
                if (second != null) {
                    return datePart + " " + hour + ":" + minute + ":" + second;
                } else {
                    return datePart + " " + hour + ":" + minute;
                }
            }
            
            return timeStr;
        } catch (Exception e) {
            return timeStr; // 出错则返回原值
        }
    }

    private Integer parseInteger(String value, String fieldName) {
        if (value == null || value.trim().isEmpty()) {
            return 0; // 默认值
        }
        
        try {
            // 清理非数字字符
            String cleanValue = value.replaceAll("[^0-9]", "");
            if (cleanValue.isEmpty()) {
                return 0;
            }
            return Integer.parseInt(cleanValue);
        } catch (NumberFormatException e) {
            System.out.println(fieldName + "格式错误，使用默认值0：" + value);
            return 0;
        }
    }

    private Boolean parseBoolean(String value, String fieldName) {
        if (value == null || value.trim().isEmpty()) {
            return false; // 默认值
        }
        
        String cleanValue = value.trim().toLowerCase();
        
        // 支持多种布尔值格式
        if ("是".equals(cleanValue) || "true".equals(cleanValue) || "1".equals(cleanValue) || "yes".equals(cleanValue)) {
            return true;
        } else if ("否".equals(cleanValue) || "false".equals(cleanValue) || "0".equals(cleanValue) || "no".equals(cleanValue)) {
            return false;
        } else {
            System.out.println(fieldName + "格式错误，使用默认值false：" + value);
            return false;
        }
    }
}